-- UIComment
-- Create by cheny3 Nov/6/2015
-- 评论系统界面
-- 传入参数data = { ["title"] = "标题", ["type"] = "pet_1"}

require "game/ui/form/comment/UICommentInput"

UIComment = class("UIComment",function()
    return cc.Layer:create()
end)

function UIComment.create(data)
    return UIComment.new(data);
end

-- 内部函数声明
local resize;
local sortTitles;
local SHOW_NUM = 10;           -- 单次界面最多显示
local COMMENT_SPACING = 15;     -- 评论间距
local LINE_HEIGHT = 26;        -- 评论字行高
local SHOW_MORE_HEIGHT = 55;   -- 【展开更多】行高度
local BG_LEFT_HIGHT = 65;      -- 单个评论预留高度

-- 构造函数
function UIComment:ctor(data)
    self:setName("UIComment");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/comment/Comment.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.BONUS_NOTIFY_ZORDER + 1);

    self.lang = CommentM.getCommentLang();

    -- 清空数据
    CommentM.clearLocalRecords();

    -- 相关数据
    self.data = data;

    -- 重绘
    self:redraw();

    -- 容器原本内高
    local scrollView = findChildByName(self.node, "CT/scroll_view");
    self.oriHeight = scrollView:getInnerContainerSize().height;

    -- 注册点击事件
    self:registerTouchEvent();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 适配
    resize(node);
end

-- 本地化语言切换
function UIComment:changeLang(lang)
    if self.lang == lang or CommentM.hideLocalChange() then
        return;
    end

    -- 设置
    CommentM.setCommentLang(lang);
    self.lang = lang;

    self:redrawLang();
end

-- 玩家增加重绘后本地重绘
function UIComment:redrawLang()
    -- 重绘界面前十条
    self.no_more = false;
    local scrollView = findChildByName(self.node, "CT/scroll_view");
    scrollView:removeAllChildren();
    self.nextNode = nil;
    self.childList = nil;
    self.index = 1;
    self.locationHeight = 0;

    -- 清空数据
    CommentM.clearLocalRecords();

    -- 请求数据
    self:tryRequestData();

    local btnLang = findChildByName(self.node, "CT/lang");
    if self.lang then
        btnLang:loadTexture(getSettingIconPath("system", "open"));
    else
        btnLang:loadTexture(getSettingIconPath("system", "close"));
    end
end

-- 重绘
function UIComment:redraw()
    -- 主标题
    local title = findChildByName(self.node, "CT/title");
    title:setString(self.data["title"]);
    TextStyleM.setTitleStyle(title);

    if CommentM.hideLocalChange() then
        -- 隐藏掉了
        return;
    end

    local btnLang = findChildByName(self.node, "CT/lang");
    if self.lang then
        btnLang:loadTexture(getSettingIconPath("system", "open"));
    else
        btnLang:loadTexture(getSettingIconPath("system", "close"));
    end
    btnLang:setVisible(true);
    btnLang:setPosition(cc.p(-220, 320));

    local subTitle = findChildByName(self.node ,"CT/sub_title");
    subTitle:setString(getLocStr("comment_loc"));
    TextStyleM.setSubheadStyle(subTitle);
    subTitle:setVisible(true);
    subTitle:setPosition(cc.p(-200, 320));
    subTitle:setScale(0.8);
end

-- 玩家增加重绘后本地重绘
function UIComment:userAddComment()
    -- 重绘界面前十条
    self.no_more = false;
    local scrollView = findChildByName(self.node, "CT/scroll_view");
    scrollView:removeAllChildren();
    self.nextNode = nil;
    self.childList = nil;
    self.index = 1;
    self.locationHeight = 0;
    self:redrawCommentsIndexLimit(1, 10);
end

-- 收集数据
function UIComment:getShowData()
    -- 获取数据出来
    self.AllCommentRecords = CommentM.getAllData();

    if self.lang then
        self.commentRecords = self.AllCommentRecords; --CommentM.getAllDataBylang(self.lang);
    else
        self.commentRecords = self.AllCommentRecords;
    end

    -- 修正下换行的问题
    self:fixContentSymbol(self.commentRecords);

    -- 整体数据下标
    self.allIndex = #self.AllCommentRecords;
end

-- 绘制评论，需要等待数据达到
function UIComment:redrawCommentsIndexLimit(index1, index2)
    -- 清除空内容提示
    local scrollView = findChildByName(self.node, "CT/scroll_view");
    if scrollView.noCommentTip then
        scrollView:removeChild(scrollView.noCommentTip);
    end

    -- 还原容器内高
    scrollView:setInnerContainerSize(cc.size(scrollView:getInnerContainerSize().width, self.oriHeight));

    -- 获取数据出来
    self:getShowData();

    local scrollView = findChildByName(self.node, "CT/scroll_view");
    self.childList = self.childList or {};
    self.scrollViewHight = COMMENT_SPACING;

    -- 计算范围（只创建最新的数据节点）
    -- 原来的节点重新布局即可
    -- local startIndex = math.max(index1, 1);
    local startIndex = self.index;
    local endIndex = math.min(#self.commentRecords, index2);
    local allIndex = math.min(#self.AllCommentRecords, index2);

    if self.nextNode then
        table.remove(self.childList, #self.childList);
        self.nextNode:setVisible(false);
        self.nextNode = nil;
    end

    -- 当前需要显示的条数
    self.curShowCount = endIndex - startIndex + 1;

    -- 更新下标
    self.index = endIndex + 1;

    -- 先创建出来所有的节点再统一去布局
    for i = startIndex, endIndex do
        local child = cc.CSLoader:createNode("layout/comment/CommentItem.csb");
        local commentInfo = self.commentRecords[i];
        self:initItem(child, commentInfo);
    end

    -- 展开查看更多
    local nextNode = cc.CSLoader:createNode("layout/comment/CommentItem.csb");
    self:redrawShowMore(nextNode);

    -- 统一计算内高
    for i = 1, #self.childList do
        local child = self.childList[i];
        self.scrollViewHight = self.scrollViewHight + child.bgHeight + COMMENT_SPACING;
        if i == #self.childList then
            self.scrollViewHight = self.scrollViewHight + 8;
        end
    end

    -- 设置容器内高
    if self.oriHeight > self.scrollViewHight then
        self.scrollViewHight = self.oriHeight;
    end
    scrollView:setInnerContainerSize(cc.size(scrollView:getInnerContainerSize().width, self.scrollViewHight));

    -- 统一布局
    local leftGap = -5;
    for i = 1, #self.childList do
        local child = self.childList[i];

        self.scrollViewHight = self.scrollViewHight - COMMENT_SPACING;

        local posY = self.scrollViewHight - 100;
        local posX = scrollView:getInnerContainerSize().width / 2 + leftGap;

        self.scrollViewHight = self.scrollViewHight - child.bgHeight;
        child:setPosition(cc.p(posX, posY));

        if not child.addAlready then
            -- 新的节点，添加上
            scrollView:addChild(child);
            child.addAlready = true;
        end
    end

    -- 添加滚动条
    if self.indicator then
        scrollView:getParent():removeChild(self.indicator);
        ScrollTool.removeEventListener(scrollView);
    end

    UIIndicator.attach(scrollView);
    self.indicator = scrollView:getParent():getChildByName("UIIndicator");

    if self.curShowCount >= SHOW_NUM and self.locationHeight then
        -- 滑到发起请求时的底部
        scrollView:jumpToPercentVertical((1 - self.locationHeight / scrollView:getInnerContainerSize().height) * 100);
    end
end

-- 绘制查看更多
function UIComment:redrawShowMore(nextNode)
    local tipLabel = nextNode:getChildByName("name");
    local clickBtn = nextNode:getChildByName("praise");
    local bg = nextNode:getChildByName("bg");
    local dateText = nextNode:getChildByName("date");
    nextNode.next = true;

    clickBtn:setScale(0.65);
    clickBtn:setPosition(cc.p(215, 73));

    tipLabel:setString(getLocStr("comment_show_more"));
    tipLabel:setFontSize(TextStyleM.TEXT_SIZE_SMALL2 + 2);
    tipLabel:setTextColor(TextStyleM.TEXT_COLOR_YELLOW_BROWN);
    dateText:setVisible(false);
    tipLabel:setScale(0.92);
    tipLabel:setPosition(cc.p(-223, 73));

    bg:loadTexture(getTitleBgIconPath("point_blue"));
    bg:setOpacity(200);
    -- 底图不要显示了 SLIMEC-6367
    bg:setVisible(false);

    local finalHight = SHOW_MORE_HEIGHT;
    nextNode.bgHeight = finalHight;
    bg:setContentSize(bg:getContentSize().width, finalHight);

    bg:setContentSize(bg:getContentSize().width, finalHight);

    clickBtn:loadTexture(getCommentIconPath("show_more"));

    local oriScale = clickBtn:getScale();
    local function onClick(sender, eventType)
        -- 点击时的回调
        if eventType == ccui.TouchEventType.began then
            clickBtn:setScale(oriScale - 0.1);
        elseif eventType == ccui.TouchEventType.canceled then
            clickBtn:setScale(oriScale);
        elseif eventType == ccui.TouchEventType.ended then
            clickBtn:setScale(oriScale);
            -- 确定定位
            local scrollView = findChildByName(self.node, "CT/scroll_view");
            self.locationHeight = scrollView:getInnerContainerSize().height;
            if (self.index + SHOW_NUM - 1) <= #self.commentRecords then
                self:redrawCommentsIndexLimit(1, self.index + SHOW_NUM - 1);
            else
                -- 没有更多数据了，去请求一下
                showCommunicatingForm();

                local btnNew = findChildByName(self.node, "BT/btn_new");
                -- 评论按钮置灰
                btnNew:setBright(false);
                btnNew:setTouchEnabled(false);

                self.waitClass = {"lastest"};
                self.has_data = false;

                CommentM.requestLastestComment(self.data["type"], self.allIndex, self.allIndex + SHOW_NUM);

                self.needWait = true;

                -- 超过一定时间认为是GS/BS某处获取信息挂了
                -- 直接关掉界面提示获取数据失败
                local function overTime()
                    if #self.waitClass > 0 and self.needWait then
                        closeCommunicatingForm();
                        -- 提示获取数据失败
                        alert(getLocStr("get_comments_fail_tip"));
                    end
                end
                performWithDelay(self, overTime, 30);

                return;
            end
        end
    end
    clickBtn:addTouchEventListener(onClick);
    self.nextNode = nil;

    -- 如果被服务器告知没有更多了或者
    if not self.no_more then
        -- 可能还有更多内容，则加入到self.childList
        table.insert(self.childList, nextNode);
        self.nextNode = nextNode;
    end
end

-- 处理点赞
function UIComment:praiseComment(commentInfo)
    -- 点赞
    if commentInfo["user_rid"] == ME.user.rid then
        -- 自己发布的帖子
        return;
    end

    -- 尝试加进记录
    self.addPraiseList = self.addPraiseList or {};

    if commentInfo["has_praise"] == 1 then
        -- 原本的数据就是点赞过的，这里直接返回即可
        return;
    else
        -- 加入返回发送点赞命令数组中
        table.insert(self.addPraiseList, commentInfo["rid"]);
    end
end

-- 绘制单个评论
function UIComment:initItem(child, commentInfo)
    local nameLabel = child:getChildByName("name");
    local numLabel = child:getChildByName("num");
    local praise = child:getChildByName("praise");
    local contentLabel = child:getChildByName("content");
    local bg = child:getChildByName("bg");
    local dateText = child:getChildByName("date");

    numLabel:setPositionX(numLabel:getPositionX() + 10);
    numLabel:setPositionY(numLabel:getPositionY() - 2);
    nameLabel:setPositionY(nameLabel:getPositionY() - 3);
    contentLabel:setPositionX(contentLabel:getPositionX() + 10);

    bg:loadTexture(getTitleBgIconPath("point_blue"));
    bg:setOpacity(200);

    -- 点赞按钮设置成80%
    praise:setScale(0.65);
    praise:setPosition(cc.p(217, 73));

    -- 姓名颜色
    local nameColor = TextStyleM.TEXT_COLOR_BLUE;
    if commentInfo["user_rid"] == ME.user.rid then
        nameColor = TextStyleM.TEXT_COLOR_YELLOW_BROWN;
    end

    -- 日期/点赞数纵坐标
    local numPosY = 71;

    -- 为解决系统字体变细情况，
    -- 这里字号统一加大两号再缩小label
    nameLabel:setString(getNickName(commentInfo["nickname"]));
    numLabel:setString(math.max(commentInfo["praise"], 0));
    contentLabel:setString(commentInfo["content"]);
    nameLabel:setFontSize(TextStyleM.TEXT_SIZE_SMALL2 + 2);
    nameLabel:setTextColor(nameColor);
    numLabel:setFontSize(TextStyleM.TEXT_SIZE_TINY2 + 1);
    numLabel:setTextColor(TextStyleM.TEXT_COLOR_GRAY);
    nameLabel:setScale(0.85);
    numLabel:setScale(0.92);
    numLabel:setPositionY(numPosY);

    -- 显示时间
    local posX = nameLabel:getPositionX() + getRealContentSize(nameLabel).width;
    dateText:setPosition(cc.p(posX, numPosY));
    local t = os.date("*t", commentInfo["create_time"] - TimeM.getTimeOffsetDifference());
    dateText:setString(string.format(getLocStr("comment_date"), t.year, t.month, t.day));
    dateText:setAnchorPoint(0, 0.5);
    dateText:setFontSize(TextStyleM.TEXT_SIZE_TINY2 + 1);
    dateText:setTextColor(TextStyleM.TEXT_COLOR_GRAY);
    dateText:setScale(0.92);

    -- 用系统字
    -- 限制单方向自适应:限制宽度，尽可能放大高度
    contentLabel:setFontSize(TextStyleM.TEXT_SIZE_SMALL2 + 2);
    contentLabel:setTextColor(TextStyleM.TEXT_COLOR_DARK_BROWN);
    contentLabel:setScale(0.85);

    local oriScale = praise:getScale();

    local function onClick(sender, eventType)
        -- 点击时的回调
        if praise.hasPraise then
            return;
        end
        if eventType == ccui.TouchEventType.began then
            praise:setScale(oriScale - 0.1);
        elseif eventType == ccui.TouchEventType.canceled then
            praise:setScale(oriScale);
        elseif eventType == ccui.TouchEventType.ended then
            praise:setScale(oriScale);

            if praise.hasPraise then
                -- 不允许取消赞
                alert(getLocStr("has_praise_already"));
            else
                -- 点赞
                if commentInfo["user_rid"] == ME.user.rid then
                    -- 自己发布的帖子
                    alert(getLocStr("praise_limit_self"));
                    return;
                end

                -- 动画效果
                praise:setOpacity(50);
                local scaleUp = cc.ScaleTo:create(0.1, oriScale * 2.0);
                local scaleDown = cc.ScaleTo:create(0.4, 0.8);
                praise:runAction(cc.Sequence:create(scaleUp, scaleDown));
                local function callback()
                    praise:setOpacity(255);
                end
                performWithDelay(self, callback, 0.5);

                praise:setPosition(cc.p(207, 73));
                --numLabel:setPositionX(numLabel:getPositionX() + 8);

                praise:loadTexture(getCommentIconPath("praise_already"));
                praise.hasPraise = true;
                -- 修改数字
                numLabel:setString(commentInfo["praise"] + 1);

                -- 逻辑处理
                self:praiseComment(commentInfo);
            end
        end
    end

    local addFlag = false;
    self.addPraiseList = self.addPraiseList or {};
    for index, rid in pairs(self.addPraiseList) do
        if rid == commentInfo["rid"] then
            addFlag = true;
            break;
        end
    end

    if commentInfo["has_praise"] == 1 or addFlag then
        -- 已经赞过了
        praise:loadTexture(getCommentIconPath("praise_already"));
        praise.hasPraise = true;
        praise:setScale(0.8);
        praise:setPosition(cc.p(207, 73));
        --numLabel:setPositionX(numLabel:getPositionX() + 8);

        if addFlag then
            numLabel:setString(commentInfo["praise"] + 1);
        end
    else
        -- 没赞过
        praise:loadTexture(getCommentIconPath("praise"));
        praise.hasPraise = false;
        praise:setPosition(cc.p(215, 73));
    end

    praise:addTouchEventListener(onClick);

    local bgHight = getRealContentSize(bg).height;

    -- 系统字label没有行高，这里用一个测试label来计算行数
    local testLabel = ccui.Text:create();
    TextStyleM.setTextStyle(testLabel, TextStyleM.TEXT_SIZE_SMALL2,
        TextStyleM.TEXT_COLOR_BROWN_YELLOW, nil, nil, nil,nil, 20);
    testLabel:setString(commentInfo["content"]);
    testLabel:setFontSize(TextStyleM.TEXT_SIZE_SMALL2);
    local labelHeight = getRealContentSize(contentLabel).height;
    -- 这里暂用宽度去计算行数
    -- 以便计算背景高度
    local lineNum = math.max(math.ceil(getRealContentSize(contentLabel).width / 540),
       contentLabel:getVirtualRenderer():getStringNumLines());
    local contentHight = getRealContentSize(contentLabel).height;
    local finalHight = math.max(lineNum * LINE_HEIGHT + BG_LEFT_HIGHT, labelHeight + BG_LEFT_HIGHT - 20);
    bg:setContentSize(bg:getContentSize().width, finalHight);

    child.bgHeight = finalHight;

    -- 底图不要显示了 SLIMEC-6367
    bg:setVisible(false);
    local line = ccui.ImageView:create(getTalentIconPath("line"));
    line:setScaleX(1.0);
    line:setPosition(cc.p(-10, -finalHight + 90));
    child:addChild(line);

    table.insert(self.childList, child);
end

-- 注册点击事件
function UIComment:registerTouchEvent()
    local btnLang = findChildByName(self.node, "CT/lang");
    local function onLangClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if self.lang then
                self:changeLang();
            else
                self:changeLang(getLang());
            end
        end
    end
    btnLang:addTouchEventListener(onLangClick);

    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIComment");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    local canNotComment = false;
    local _, _, typeName, classId = string.find(self.data["type"], "(%a+)_(%d+)");
    if typeName == "pet" then
        -- 获取玩家宠物
        local pet = PetM.getMyPet(tonumber(classId));
        if not pet then
            canNotComment = true;
        end
    elseif typeName == "ship" then
        if not NewAirShipM.hasOwnShip(tonumber(classId)) then
            canNotComment = true;
        end
    end

    local btnNew = findChildByName(self.node, "BT/btn_new");
    local function onNewClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            local function callback()
                -- 玩家试图评论，必须输入昵称和国籍
                if TopM.isFirstVisitTop() then
                    self:showRankNickInput();
                    return;
                end

                if canNotComment then
                    -- 不能评论
                    alert(getLocStr("can_not_comment_tip_" .. typeName));
                    return;
                end

                -- 打开评论输入界面
                UIMgr.getCurrentScene():removeFormByName("UICommentInput");
                local uiCommentInput = UICommentInput.create(self.data["type"]);
                UIMgr.getCurrentScene():addForm(uiCommentInput);
            end
            checkIfGuestNeedBind(callback);
        end
    end
    btnNew:addTouchEventListener(onNewClick);
    TextStyleM.setTextStyle(btnNew, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnNew:setTitleText(getLocStr("btn_text_new_comment"));
end

-- 显示昵称国家输入界面
function UIComment:showRankNickInput()
    closeFormByName("UIRankNick")
    local uiForm = UIRankNick.create();
    UIMgr.getCurrentScene():addForm(uiForm);
end

-- 处理没有数据情况
function UIComment:noComments()
    local scrollView = findChildByName(self.node, "CT/scroll_view");
    scrollView:removeAllChildren();
    self.nextNode = nil;
    self.childList = nil;
    self.index = 1;
    self.locationHeight = 0;

    local textLabel = ccui.Text:create();
    local posX = scrollView:getInnerContainerSize().width / 2;
    local posY = scrollView:getInnerContainerSize().height / 5 * 3;

    TextStyleM.setTextStyle(textLabel, TextStyleM.TEXT_SIZE_LARGE, TextStyleM.TEXT_COLOR_GRAY);
    textLabel:setPosition(cc.p(posX, posY));
    textLabel:setAnchorPoint(0.5, 0.5);
    textLabel:setString(getLocStr("no_comment_tip"));

    scrollView:addChild(textLabel);
    scrollView.noCommentTip = textLabel;
end

-- 数据到达处理函数
function UIComment:whenCommentsArrive(para)
    local class = para["class"];
    local has_data = para["has_data"];
    local btnNew = findChildByName(self.node, "BT/btn_new");

    for index, logClass in pairs(self.waitClass) do
        if logClass == class then
            table.remove(self.waitClass, index);
            break;
        end
    end

    self.has_data = self.has_data or has_data or false;

    if #self.waitClass == 0 then
        -- 数据都到了
        self.needWait = false;

        -- 评论按钮可见
        btnNew:setBright(true);
        btnNew:setTouchEnabled(true);

        if self.has_data or tonumber(self.index) <= tonumber(self.allIndex) then
            -- 有新数据
            local function callback()
                closeCommunicatingForm();
                self:redrawCommentsIndexLimit(1, self.index + SHOW_NUM - 1);
            end
            performWithDelay(self, callback, 0.2);
        else
            closeCommunicatingForm();
            -- 完全没有该评论的数据
            if not self.AllCommentRecords or #self.AllCommentRecords <= 0 then
                self:noComments();
                return;
            end
            -- 没有新数据提示一下，隐藏更多显示
            self.no_more = true;
            alert(getLocStr("no_more_comment_tip"));
            if self.nextNode then
                self.nextNode:setVisible(false);
            end
            self.has_data = false;
        end
    end
end

-- 进入界面请求数据
function UIComment:tryRequestData()
    self.index = 1;

    -- 请求数据(点赞前五/最新前十)
    local commentType = self.data["type"];
    CommentM.requestTopPraiseComment(commentType);
    CommentM.requestLastestComment(commentType, 1, 10);
    self.needWait = true;
    self.waitClass = {"top", "lastest"};

    local btnNew = findChildByName(self.node, "BT/btn_new");
    -- 需要加载中界面
    local function callback()
        if self.needWait then
            showCommunicatingForm();

            -- 评论按钮置灰
            btnNew:setBright(false);
            btnNew:setTouchEnabled(false);

            -- 超过一定时间认为是GS/BS某处获取信息挂了
            -- 直接关掉界面提示获取数据失败
            local function overTime()
                if #self.waitClass > 0 and self.needWait then
                    closeCommunicatingForm();
                    -- 直接绘制空数据
                    self:noComments();
                    alert(getLocStr("get_comments_fail_tip"));
                end
            end
            performWithDelay(self, overTime, 30);
        end
    end
    performWithDelay(self, callback, 0.01);
end

-- 修正评论内容中的换行符
function UIComment:fixContentSymbol(allData)
    local limitCount = FormulaM.invoke("CALC_COMMENT_WORDS_LIMIT");

    for _, data in ipairs(allData) do
        local content = data["content"];
        local index = string.find(content, " ", 1)
        -- 去掉头部所有空格
        while index and index == 1 do
            content = string.gsub(content, " ", "", 1);
            index = string.find(content, " ", 1);
        end

        -- 去掉所有的\n
        content = string.gsub(content, "\n", "");

        if content == "" then
            content = getLocStr("please_input_comment");
        end

        local retArr = string.fixContent(content, TextStyleM.TEXT_SIZE_SMALL2, 450);
        local changeContent = "";
        for index, text in pairs(retArr) do
            changeContent = changeContent .. text;
            if index ~= #retArr then
                changeContent = changeContent .. "\n";
                if string.getByteCount(changeContent) >= limitCount then
                    -- 超过的直接不要了
                    break;
                end
            end
        end
        data["content"] = changeContent;
    end
end

-- 注册事件处理回调函数
function UIComment:registerEventCallback()
    local btnNew = findChildByName(self.node, "BT/btn_new");
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIComment 界面析构清理");
            EventMgr.removeAll("UIComment");

            -- 关闭通讯中界面
            closeCommunicatingForm();

            -- 发送相关命令
            if self.addPraiseList and #self.addPraiseList > 0 then
                CommentM.addPraise(self.data["type"], self.addPraiseList);
            end
            if self.cancelPraiseList and #self.cancelPraiseList > 0 then
                CommentM.cancelPraise(self.data["type"], self.cancelPraiseList);
            end

            -- 界面恢复显示
            local forms = {"UIEnterDungeon", "UIHeroDetailInfo", "UIHeroInfo", "UIMonsterInfo", "UIBossMonsterInfo", "UIAirShipHandBook"};
            for _, name in pairs(forms) do
                local uiForm = UIMgr.getCurrentScene():getFormByName(name);
                if uiForm then
                    uiForm:setVisible(true);
                end
            end

        elseif ev == "enter" then
            -- 获得焦点
            EventMgr.register("UIComment", event.FOCUS_CHANGED, function(para)
                if para["get"] == "UIComment" then
                    -- TODO
                end
            end);

            -- 相关界面隐藏，降低GL calls
            local forms = {"UIEnterDungeon", "UIHeroDetailInfo", "UIHeroInfo", "UIMonsterInfo", "UIBossMonsterInfo", "UIAirShipHandBook"};
            for _, name in pairs(forms) do
                local uiForm = UIMgr.getCurrentScene():getFormByName(name);
                if uiForm then
                    uiForm:setVisible(false);
                end
            end

            -- 信息到达
            EventMgr.register("UIComment", event.BBS_COMMENTS_ALREADY, function(para)
                self:whenCommentsArrive(para);
            end);

            -- 发布评论结果
            EventMgr.register("UIComment", event.POST_NEW_COMMENT_RESULT, function(para)
                local result = para.result;
                if result ~= "ok" then
                    -- 添加失败
                    alert(getLocStr(result));
                    CommentM.deleteNewPostComment();
                else
                    -- 添加成功
                    self:userAddComment();
                    alert(getLocStr("add_comment_success_tip"));
                end
            end);

            -- 请求数据
            self:tryRequestData();
        end
    end);
end

-- 适配
function resize(node)
    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end
